package com.zat.mes.andrmes.dofun.system

import android.content.Intent
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.ListPopupWindow
import androidx.core.content.ContextCompat
import com.google.gson.Gson
import com.love.zywanandroid.retrofit.RetrofitManager
import com.love.zywanandroid.retrofit.api.ApiService
import com.zat.mes.andrmes.R
import com.zat.mes.andrmes.base.BaseActivity
import com.zat.mes.andrmes.data.BaseResponse
import com.zat.mes.andrmes.data.LoginResultBean
import com.zat.mes.andrmes.dofun.main.MainActivity
import com.zat.mes.andrmes.dofun.system.adapter.CompanyAdapter
import com.zat.mes.andrmes.global.CompanionType
import com.zat.mes.andrmes.retrofit.callback.MesCallBack
import com.zat.mes.andrmes.utils.Md5Util
import com.zat.mes.andrmes.utils.PreferencesUtil
import com.zat.mes.andrmes.utils.SpannableStrUtil
import com.zat.mes.andrmes.utils.StatusBarUtils
import kotlinx.android.synthetic.main.activity_login.*
import okhttp3.RequestBody
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Response

/**
 * 登录activity
 */
class LoginActivity : BaseActivity(), View.OnClickListener {

    /**
     * 公司
     */
//    var comResultBeanList: List<ComResultBean>? = null
    var listPopupWindow: ListPopupWindow? = null
//    var corpId: String? = null
    var corpName: String? = null
//    var accessToken = ""
    /**
     *下拉模糊搜索匹配的数据
     */
//    var strList: MutableList<ComResultBean> = ArrayList()
    /**
     * 所有的下拉数据
     */
//    var allStrList: MutableList<ComResultBean> = ArrayList()
    /**
     * 下拉适配器
     */
    var arrayAdapter: CompanyAdapter? = null


    override fun init() {
        setContentView(R.layout.activity_login)
        initView()
        addListener()
//        getAccessToken()
//        loadModel()

    }

//    private fun loadModel() {
//        val loginViewModel = ViewModelProvider(this).get(LoginViewModel::class.java)
//        loginViewModel.getComList().observe(this, Observer<List<ComResultBean>> {
//            closeLoading()
//            if (it == null) {
//                showToast(getString(R.string.net_request_fail))
//            } else {
//                allStrList.clear()
//                for (bean in it!!) {
//                    if (!TextUtils.isEmpty(bean?.corpName)) {
//                        allStrList.add(bean)
//                    }
//                }
//            }
//        })
//    }
    /**
     * 初始化数据
     */
    fun initView() {
        tvLoginTip.setText(
            SpannableStrUtil.getColorSpannable(
                tvLoginTip.text.toString(), 0, 5,
                ContextCompat.getColor(this@LoginActivity, R.color.color_text_red)
            )
        )
        val loginParam = PreferencesUtil.getString(CompanionType.LOGIN_PARAM)
        if (!TextUtils.isEmpty(loginParam)) {
            try {
                val jsonObject = JSONObject(loginParam)
                corpName = jsonObject.optString("corpName")
                etLoginCom.setText(corpName)
                etLoginName.setText(jsonObject.optString("EmpEnName"))
                etLoginPwd.setText(jsonObject.optString("password"))
            } catch (e: Exception) {
            }

        }
    }

    /**
     * 设置状态栏
     */
    override fun setStatusBar() {
        StatusBarUtils.fullScreen(this)
    }
    /**
     * 添加监听
     */
    fun addListener() {
        btnLogin.setOnClickListener(this)
        ivLoginNameClear.setOnClickListener(this)
        ivLoginPwdClear.setOnClickListener(this)
        tvLoginForget.setOnClickListener(this)

        etLoginCom.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                setErrorGone()
//                if (!TextUtils.isEmpty(s.toString())) {
//                    if (listPopupWindow == null) {
//                        showListPopWindow()
//                    }
//                    if (!listPopupWindow?.isShowing!!) {
//                        notifyPopup(s)
//                        listPopupWindow?.show()
//                    } else {
//                        notifyPopup(s)
//                    }
//
//
//                } else {
//                    listPopupWindow?.dismiss()
//                }
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

        })
        etLoginName.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                setErrorGone()
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })
        etLoginPwd.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                setErrorGone()
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })
    }

    /**
     * 刷新筛选框
     */
//    private fun notifyPopup(s: Editable?) {
//        strList.clear()
//        strList.addAll(getMatch(s.toString()))
//        arrayAdapter?.notifyDataSetChanged()
//    }

    /**
     * 错误信息隐藏
     */
    private fun setErrorGone() {
        tvLoginError.visibility = View.INVISIBLE
        tvLoginError.text = ""
    }

    /**
     * 请求登录
     */
    fun login() {
        if (TextUtils.isEmpty(etLoginCom.text)) {
            tvLoginError.visibility = View.VISIBLE
            tvLoginError.text = getString(R.string.text_input_comname)
            return
        }
        if (TextUtils.isEmpty(etLoginName.text)) {
            tvLoginError.visibility = View.VISIBLE
            tvLoginError.text = getString(R.string.text_input_empname)
            return
        }
        if (TextUtils.isEmpty(etLoginPwd.text)) {
            tvLoginError.visibility = View.VISIBLE
            tvLoginError.text = getString(R.string.text_input_pwd)
            return
        }
        if (etLoginPwd.text.length < 8) {
            tvLoginError.visibility = View.VISIBLE
            tvLoginError.text = getString(R.string.text_input_pwd_check)
            return
        }
        corpName = etLoginCom.text.toString()
        showLoading()
        val jsonObject = JSONObject()
        jsonObject.put("corpName", corpName)
        if("海织云".equals(corpName)) {
            jsonObject.put("password",etLoginPwd.text.toString())
        }else{
            jsonObject.put("password", Md5Util.MD5(etLoginPwd.text.toString()))
        }
        jsonObject.put("EmpEnName", etLoginName.text.toString())
//        jsonObject.put("access_token", accessToken)
        val requestBody: RequestBody =
            RequestBody.create(RetrofitManager.JOSNTYPE, jsonObject.toString())
        RetrofitManager.run {
            apiService(ApiService::class.java).login(requestBody)
                .enqueue(object : MesCallBack<BaseResponse<LoginResultBean>>() {


                    override fun onSuccessful(
                        call: Call<BaseResponse<LoginResultBean>>?,
                        response: Response<BaseResponse<LoginResultBean>>?
                    ) {
                        closeLoading()

                        if (response?.body()?.success != null) {
                            if (response?.body()?.success!!) {
                                //保存本地密码为铭文
                                jsonObject.put("password", etLoginPwd.text.toString())
                                //保存登录时的信息
                                PreferencesUtil.saveValue(
                                    CompanionType.LOGIN_PARAM,
                                    jsonObject.toString()
                                );
                                //保存登录后人员企业等信息
                                PreferencesUtil.saveValue(
                                    CompanionType.LOGIN_RESULT,
                                    Gson().toJson(response?.body()?.result)
                                )
                                response?.body()?.result?.token?.let {
                                    PreferencesUtil.saveValue(
                                        CompanionType.TOKEN,
                                        it
                                    )
                                }
                                response?.body()?.result?.corpid.let {
                                    PreferencesUtil.saveValue(
                                        CompanionType.CORPID,
                                        it.toString()
                                    )
                                }
//                                if ("1".equals(response?.body()?.result?.isfirst)){
//                                    //未注册海尔
//                                    val intent = Intent(this@LoginActivity,PhoneVerActivity::class.java)
//                                    intent.putExtra("empId",response?.body()?.result?.empid.toString())
//                                    intent.putExtra("accessToken",accessToken)
//                                    startActivity(intent)
//                                    finish()
//                                }else{
                                startBaseActivity(
                                    Intent(
                                        this@LoginActivity,
                                        MainActivity::class.java
                                    )
                                )

                                finish()
//                                }

                            } else {
                                tvLoginError.setText(response?.body()?.message)
                                tvLoginError.visibility = View.VISIBLE
                            }
                        } else {
                            tvLoginError.setText(getString(R.string.net_request_fail))
                            tvLoginError.visibility = View.VISIBLE
                        }
                    }

                })
        }
    }

    override fun onClick(v: View?) {
        when (v) {
            btnLogin -> login()
            ivLoginNameClear -> etLoginName.setText("")
            ivLoginPwdClear -> etLoginPwd.setText("")
            tvLoginForget -> {
                AlertDialog.Builder(this)
                    .setMessage(getString(R.string.text_contack_admin))
                    .setNegativeButton(getString(R.string.sure), null)
                    .show()
            }
        }
    }

    /**
     * 初始化 popup
     */
//    fun showListPopWindow() {
//        listPopupWindow = ListPopupWindow(this);
//        arrayAdapter = CompanyAdapter(this, strList)
//        listPopupWindow?.setAdapter(arrayAdapter)
//        listPopupWindow?.setAnchorView(etLoginCom);//设置listpopowindow和哪个控件相邻
////        listPopupWindow?.setModal(true);//指定listpopwindow是否阻止在显示的时候将内容输入其他窗口
//
//
//        listPopupWindow?.setOnItemClickListener(object : AdapterView.OnItemClickListener {
//            override fun onItemClick(
//                parent: AdapterView<*>?,
//                view: View?,
//                position: Int,
//                id: Long
//            ) {
//                corpName = strList.get(position).corpName
//                corpId = strList?.get(position)?.corpId
//                etLoginCom.setText(corpName)
//                etLoginCom.setSelection(etLoginCom.text.length)
//                listPopupWindow?.dismiss()
//            }
//        });
//    }

    /**
     * 模糊匹配
     */
//    fun getMatch(
//        sub: String?
//    ): MutableList<ComResultBean> {
//        val matchList: MutableList<ComResultBean> = ArrayList()
//        for (strList in allStrList!!) {
//            if (strList.corpName.contains(sub!!)) {
//                matchList.add(strList)
//            }
//        }
//        return matchList
//    }

    /**
     * 获取token
     */
//    private fun getAccessToken() {
//        RetrofitManager.apiService(ApiService::class.java)
//            .getAccessToken()
//            .enqueue(object : MesCallBack<BaseResponse<String>>() {
//                override fun onSuccessful(
//                    call: Call<BaseResponse<String>>?,
//                    response: Response<BaseResponse<String>>?
//                ) {
//
//                    val result = response?.body()?.result
//                    if(!TextUtils.isEmpty(result)) {
//                        val json = JSONObject(result);
//                        accessToken = json.optString("access_token")
//                    }
//
//                }
//
//            })
//    }
}

